# '''
# Author: gaoh
# Date: 2023-08-05 17:54:38
# LastEditTime: 2023-08-05 18:39:03
# '''

from urllib.parse import urlencode
from pyquery import PyQuery as pq
import requests
import json

base_url = 'https://m.weibo.cn/api/container/getIndex?'

headers = {
    'Host': 'm.weibo.cn',
    'Referer': 'https://m.weibo.cn/u/2830678474',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
}


def get_page(page):
    params = {
        'type': 'uid',
        'value': '2830678474',
        'containerid': '1076032830678474',
        'page': page
    }
    url = base_url+urlencode(params)
    print(url)
    try:
        resp = requests.get(url, headers=headers)
        if resp.status_code == 200:
            return resp.json()
    except requests.ConnectionError as e:
        print("Error args:", e.args)


def parse_page(json):
    if json:
        items = json.get('data').get('cards')
        for item in items:
            mblog = item.get('mblog')
            yield {
                'id':mblog.get('id'),
                'text':pq(mblog.get('text')).text(),
                'attitudes':mblog.get('attitudes_count'),
                'comments':mblog.get('comments_count'),
                'reposts':mblog.get('reposts_count'),
            }

def wirte2file(content,filename='weibo.txt'):
    with open(filename,'a',encoding='utf8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')

if __name__ == '__main__':
    for i in range(1, 11):
        resp = parse_page(get_page(i))
        for data in resp:
            print(data)
            wirte2file(data)

 